<?php

namespace app\controller;

use app\service\GameService;
use think\facade\Db;

class GameController extends Base
{
    //免登录白名单
    protected array $noNeedLogin = ['login'];

    //用户登录
    public function login()
    {
        // 获取参数
        $code = $this->request->post('code', null);
        if (empty($code)) {
            return json(apiError('code不能为空'));
        }

        //平台
        $platform = $this->request->post('platform', 0);
        $nickname = $this->request->post('nickname', null);
        $avatar = $this->request->post('avatar', null);

        // 启动事务
        try {
            $res = Db::transaction(function () use ($code, $platform, $nickname, $avatar) {
                $userService = new GameService();
                $res = $userService->login($code, $platform, $nickname, $avatar);

                if (empty($res['code']) || $res['code'] !== 1) {
                    throw new \Exception('登录失败');
                }
                return $res;
            });

            return json($res);

        } catch (\Throwable $e) {
            return json(apiError($e->getMessage()));
        }
    }

}